<template>
  <wd-navbar title="内容由AI生成，请仔细甄别" custom-class="navbar-custom"></wd-navbar>
  <view
    id="chatContainer"
    class="h-[calc(100vh-140rpx-60rpx)] w-[100%] items-center flex-col flex"
    style="overflow: hidden; overflow: scroll"
    @touchstart="startDrag"
  >
    <!-- 聊天信息 -->
    <view v-for="item in data" class="w-[100%]">
      <!-- 医生对话框 -->
      <view v-if="item.type" class="mx-0 my-15rpx flex w-[100%]">
        <view class="mx-20rpx my-0">
          <img class="h-76rpx w-76rpx" src="@/static/exports/Avatar_doctor@1x.png" alt="" />
        </view>

        <view style="max-width: 80%">
          <text class="tracking-[0rpx] lh-normal text-[26rpx] font-regular text-[#979797]">
            AI医生
          </text>
          <view class="p-20rpx bg-[#ffffff] rounded-[20px]">
            <wd-text :text="item.text" :speed="50" custom-class="wd-textA" />
          </view>
        </view>
      </view>
      <!-- 患者对话框 -->
      <view v-else class="mx-0 my-15rpx justify-end flex w-[100%]">
        <view class="items-end flex-col flex max-w-[80%]">
          <text class="tracking-[0rpx] lh-normal text-[26rpx] font-regular text-[#979797]">
            患者
          </text>
          <view class="p-20rpx bg-[#ffffff] rounded-[20px]">
            <wd-text :text="item.text" :speed="50" custom-class="wd-textA" />
          </view>
        </view>
        <view class="mx-20rpx my-0">
          <img class="h-76rpx w-76rpx" src="@/static/exports/Avatar_default@1x.png" alt="" />
        </view>
      </view>
    </view>
    <!-- 加载中效果 -->
    <view v-if="loading" class="mx-0 my-15rpx flex w-[100%]">
      <view class="mx-20rpx my-0">
        <img class="h-76rpx w-76rpx" src="@/static/exports/Avatar_doctor@1x.png" alt="" />
      </view>

      <view style="max-width: 80%">
        <text class="tracking-[0rpx] lh-normal text-[26rpx] font-regular text-[#979797]">
          AI医生
        </text>
        <view class="p-20rpx bg-[#ffffff] rounded-[20px]">
          <Typewriter text="加载中..." :speed="50" />
        </view>
      </view>
    </view>
  </view>
  <!-- 底部发送框 -->
  <view class="inputa">
    <wd-button type="info" size="small" custom-class="leftButtom" @click="tabValue">
      {{ value1 ? "联网模式" : "本地模式" }}
    </wd-button>
    <wd-input
      v-model="inputValue"
      :disabled="stopSc"
      type="text"
      placeholder="AI咨询"
      :no-border="true"
      custom-class="inputType"
    />
    <wd-button
      :type="inputValue !== '' ? 'primary' : 'info'"
      size="small"
      custom-class="rightButtom"
      :disabled="stopSc"
      @click="handleClick()"
    >
      发送
    </wd-button>
  </view>
</template>

<script lang="ts" setup>
import TopNavigation from "@/components/TopNavigation.vue";
import Typewriter from "@/components/Typewriter.vue";
import axios from "axios";
import OpenAI from "openai";
//ai生成时不能再次输入内容
const stopSc = ref(false);

//拖拽停止自动触底事件
const isDragging = ref(false);
function startDrag() {
  isDragging.value = true;
}

onMounted(() => {
  document.title = "惠生 - AI问诊";
});

// 控制加载中的内容
const loading = ref(false);
// 切换本地ai和联网ai
const value1 = ref(true);
function tabValue() {
  value1.value = !value1.value;
}
//输入框数据
const inputValue = ref("");
const aiValue = ref();
//点击发送触发的事情
function handleClick() {
  if (inputValue.value) {
    console.log("发送");
    const userText = { type: false, text: inputValue.value || "" };
    aiValue.value = inputValue.value;
    inputValue.value = "";
    data.value.push(userText);
    toBottom();
    loading.value = true;
    if (value1.value) {
      loading.value = false;
      const userText = { type: true, text: "思考中..." };
      data.value.push(userText);
      isDragging.value = false;
      stopSc.value = true;
      main();
    } else {
      const axiosData = {
        model: "deepseek-r1:8b",
        prompt: aiValue.value,
        stream: false,
      };
      stopSc.value = true;
      localdeepseek(axiosData);
    }
  }
}
//对话数据
const data = ref([{ type: true, text: "AI医生随时等待您" }]);

//本地deepkeekk
function localdeepseek(value: any) {
  axios
    .post(url, value, { headers }) // 第二个参数是请求体，第三个参数是配置选项
    .then((response) => {
      const userText = {
        type: true,
        text: response.data.response,
      };
      loading.value = false;
      data.value.push(userText);
      toBottom();
      stopSc.value = false;
    })
    .catch((error) => {
      console.error("请求失败:", error.message);
    })
    .finally(() => {
      console.log("请求完成");
    });
}

const openai = new OpenAI({
  baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
  apiKey: "sk-30945a9dd38843e4a9c349abad8c4e82",
  dangerouslyAllowBrowser: true,
});

async function main() {
  const completion = await openai.chat.completions.create({
    model: "deepseek-r1",
    messages: [{ role: "user", content: aiValue.value }],
    stream: true,
    stream_options: {
      include_usage: true,
    },
  });

  for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
      if (data.value[data.value.length - 1].text != "思考中...") {
        if (chunk.choices[0].delta.reasoning_content) {
          data.value[data.value.length - 1].text =
            data.value[data.value.length - 1].text + chunk.choices[0].delta.reasoning_content || "";
        } else {
          data.value[data.value.length - 1].text =
            data.value[data.value.length - 1].text + chunk.choices[0].delta.content || "";
        }
      } else {
        data.value[data.value.length - 1].text = chunk.choices[0].delta.reasoning_content || "";
      }
    }
    if (!isDragging.value) {
      toBottom();
    }
  }
  stopSc.value = false;
}
// 收发消息+滚到底部
function toBottom() {
  nextTick(() => {
    const chatContainer = document.getElementById("chatContainer");
    if (chatContainer) {
      chatContainer.scrollTo({
        top: chatContainer.scrollHeight, // 滚动到容器的最底部
        behavior: "smooth", // 平滑滚动
      });
    }
  });
}

const url = "https://ns6t4xjg-11434.asse.devtunnels.ms/api/generate"; // 替换为你的目标URL

// 设置请求头
const headers = {
  "Content-Type": "application/json", // 默认为 application/json
};

// 监听键盘事件
document.addEventListener("keydown", (e) => {
  if (e.key == "Enter") {
    if (inputValue.value) {
      console.log("发送");
      const userText = { type: false, text: inputValue.value || "" };
      aiValue.value = inputValue.value;
      inputValue.value = "";
      data.value.push(userText);
      toBottom();
      loading.value = true;
      if (value1.value) {
        loading.value = false;
        const userText = { type: true, text: "思考中..." };
        data.value.push(userText);
        isDragging.value = false;
        stopSc.value = true;
        main();
      } else {
        const axiosData = {
          model: "deepseek-r1:8b",
          prompt: aiValue.value,
          stream: false,
        };
        stopSc.value = true;
        localdeepseek(axiosData);
      }
    }
  }
});
</script>

<style lang="scss" scoped>
.djs {
  font-size: 26rpx !important;
  font-weight: regular !important;
  line-height: normal !important;
  color: #3c3e42 !important;
  letter-spacing: 0rpx;
}
.wxts {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 90%;
  padding: 10rpx 20rpx;
  margin: 50rpx 0;
  background: #ffffff;
  border-radius: 40rpx;
}
.wxtss {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50%;
  padding: 10rpx 20rpx;
  background: #ffffff;
  border-radius: 40rpx;
}
.wxtsss {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30%;
  padding: 10rpx 20rpx;
  margin-top: 30rpx;
  margin-bottom: 50rpx;
  background: #ffffff;
  border-radius: 40rpx;
}
.inputa {
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 15rpx 0;
  background-color: #ffffff;
}
.inputType {
  width: 55%;
  padding: 18rpx 20rpx;
  // margin-left: 10rpx;
  background: #fafafa;
  border-radius: 50rpx;
}
.iconType {
  margin-left: 20rpx;
}
.wd-textA {
  width: 100% !important;
  font-size: 30rpx !important;
  font-weight: regular;
  line-height: 46rpx !important;
  color: #3c3e42 !important;
  text-align: left !important;
  letter-spacing: 0rpx;
}
.leftButtom {
  margin-left: 20rpx;
}
.rightButtom {
  margin-right: 20rpx;
}
.navbar-custom {
  font-size: 20px !important; /* 修改为你需要的字体大小 */
  color: #ff0000 !important; /* 修改为你需要的颜色 */
}
</style>
